#include <stdio.h>
#include <string.h>
#include "iic.h"
#include "mpu6050_drv.h"
#include "platform_api.h"

static uint32_t gpio_isr(void *user_data)
{
    if (1 == GIO_GetIntStatus(MPU_IIC_INT))
        printf("Mpu int\r\n");

    GIO_ClearAllIntStatus();
    return 0;
}

void setup_mpu_io_init(void)
{
	SYSCTRL_ClearClkGateMulti(0 | (1 << SYSCTRL_ITEM_APB_PinCtrl)
								| (1 << SYSCTRL_ITEM_APB_SysCtrl)
								| (1 << SYSCTRL_ITEM_APB_I2C0)
								| (1 << SYSCTRL_ITEM_APB_GPIO1));

	PINCTRL_SelI2cIn(MPU_IIC_PORT, MPU_IIC_SCK, MPU_IIC_DIO);
	PINCTRL_SetPadMux(MPU_IIC_SCK, IO_SOURCE_I2C0_SCL_OUT);
	PINCTRL_SetPadMux(MPU_IIC_DIO, IO_SOURCE_I2C0_SDA_OUT);
	SYSCTRL_ResetBlock(SYSCTRL_ITEM_APB_I2C0);
	SYSCTRL_ReleaseBlock(SYSCTRL_ITEM_APB_I2C0);	

    PINCTRL_SetPadMux(MPU_IIC_INT, IO_SOURCE_GPIO);
    GIO_SetDirection(MPU_IIC_INT, GIO_DIR_INPUT);  
    PINCTRL_Pull(MPU_IIC_INT, PINCTRL_PULL_UP);
    GIO_ConfigIntSource(MPU_IIC_INT, GIO_INT_EN_LOGIC_LOW_OR_FALLING_EDGE, GIO_INT_EDGE);
    GIO_DebounceCtrl((1 << SYSCTRL_ITEM_APB_GPIO1), 4, GIO_DB_CLK_32K);
    GIO_DebounceEn(MPU_IIC_INT, 1);
    platform_set_irq_callback(PLATFORM_CB_IRQ_GPIO1, gpio_isr, NULL);
    platform_enable_irq(PLATFORM_CB_IRQ_GPIO1,0);
    
	i2c_init(MPU_IIC_PORT);
	I2C_Enable(I2C_BASE(MPU_IIC_PORT),1);
	I2C_ConfigClkFrequency(I2C_BASE(MPU_IIC_PORT),MPU_IIC_CLOCK);
    printf("Apb clk div:%d, clk:%dhz\n", SYSCTRL_GetPClkDiv(),SYSCTRL_GetPClk());

}

uint8_t mpu6050_iic_send_byte(uint8_t addr, uint8_t reg, uint8_t len, uint8_t *data){

    uint8_t buf[len+1];
    buf[0] = reg;
    memcpy(&buf[1],data,len);
    return i2c_write(MPU_IIC_PORT,addr,buf,len+1);
}
uint8_t mpu6050_iic_receive_byte(uint8_t addr, uint8_t reg, uint8_t len, uint8_t *data){

    return i2c_read(MPU_IIC_PORT,addr,&reg,1,data,len);
}

void mpu6050_reg_int_cb(void *param)
{


}